home *** CD-ROM | disk | FTP | other *** search
/ AI Game Programming Wisdom / AIGameProgrammingWisdom.iso / SourceCode / 11 Learning / 08 Manslow / CTank.cpp < prev    next >
Encoding:
C/C++ Source or Header  |  2001-10-01  |  2.1 KB  |  69 lines

  1. //Tanks
  2. //Copyright John Manslow
  3. //29/09/2001
  4.  
  5. #include "stdafx.h"
  6. #include "CTank.h"
  7. #include "CProjectile.h"
  8.  
  9. const double pi=3.1415926535;
  10.  
  11. CTank::CTank()
  12. {
  13.     TRACE("\t\tCreating tank...");
  14.     //Initialise member variables to reasonable values
  15.     //The values will be set by the calling function so aren't too critical
  16.     dInclination=45.0*pi/180.0;
  17.     dBarrelx=1.0;
  18.     dBarrely=0.0;
  19.     dxPosition=0;
  20.     dyPosition=0;
  21.     TRACE("successful.\n");
  22. }
  23.  
  24. CTank::~CTank()
  25. {
  26.     TRACE("\t\tDestroying tank...");
  27.     TRACE("successful.\n");
  28. }
  29.  
  30. //This function tests for a collision between the projectile and a horizontal 
  31. //line at the base of the tank. Because of this simplistic model, you often 
  32. //can't hit a tank by firing a low flat shot at it. Fortunately, such shots
  33. //are usually prevented by the landscape.
  34. int CTank::nTestForProjectileTankCollision(const CProjectile * const pProjectile)
  35. {
  36.     //Record the movement of the projectile in the last time step
  37.     double dx=pProjectile->dxPosition-pProjectile->dPreviousxPosition;
  38.     double dy=pProjectile->dyPosition-pProjectile->dPreviousyPosition;
  39.  
  40.     //Compute the time the projectile would have the same y position as the tank
  41.     double dTimeOfIntersection=(dyPosition-pProjectile->dPreviousyPosition)/dy;
  42.  
  43.     //If that time is not within the current time step a collision cannot have happened
  44.     if(    dTimeOfIntersection<0.0 || 
  45.         dTimeOfIntersection>1.0)
  46.     {
  47.         //Return false to indicate no hit.
  48.         return 0;
  49.     }
  50.  
  51.     //We know that the projectile passed through the same vertical position as occupied by
  52.     //the tank in the last time step but we need to know if the projectile was close to the
  53.     //tank's horizontal position when it did so.
  54.  
  55.     //Calculate the projectile's x position when its y position was the same as that of the 
  56.     //tank
  57.     double xAtIntersection=pProjectile->dPreviousxPosition+dx*dTimeOfIntersection;
  58.  
  59.     //Test to see if it is within the length of the tank
  60.     if(    xAtIntersection<dxPosition-10.0 || 
  61.         xAtIntersection>dxPosition+12.0)
  62.     {
  63.         //If not, return 0 to indicate that there was no hit.
  64.         return 0;
  65.     }
  66.  
  67.     //Otherwise, a hit has happened, so return 1.
  68.     return 1;
  69. }